<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-popup
                v-decorator="['projectName',validatorRules.projectName]"
                :trigger-change='true'
                org-fields='id,short_name,customer_name,charger'
                dest-fields='projectId,projectName,customerShortName,projectCharger'
                code='pm_project_select'
                @callback='popupCallback'
              />
              <input v-decorator="['projectId']" v-show='false'></input>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <a-form-item label="项目经理" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['projectCharger']" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <a-form-item label="客户简称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['customerShortName']" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <a-form-item label="回访人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-user-by-dep :multi="false" v-decorator="['visitor',validatorRules.visitor]" :disabled="model.bpmStatus == '3'"/>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <a-form-item label="被访人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['contactPerson',validatorRules.contactPerson]" placeholder="请输入用户名称" :disabled="model.bpmStatus == '3'"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <a-form-item label="被访人角色" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['contactPersonRole',validatorRules.contactPersonRole]" placeholder="请输入用户角色" :disabled="model.bpmStatus == '3'"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <a-form-item label="问题提出日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择提出日期" v-decorator="['questionDate',validatorRules.questionDate]" :trigger-change="true" style="width: 100%" :disabled="model.bpmStatus == '3'"/>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <a-form-item label="期望完成日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择期望完成日期" v-decorator="['hopeDate',validatorRules.hopeDate]" :trigger-change="true" style="width: 100%" :disabled="model.bpmStatus == '3'"/>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <a-form-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-upload v-decorator="['files', validatorRules.accessories]" :trigger-change="true" :disabled="model.bpmStatus == '3'"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="售后问题明细" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="postSaleQuestionItemTable.loading"
          :columns="model.bpmStatus == '3' ? postSaleQuestionItemTable.columns1:postSaleQuestionItemTable.columns"
          :dataSource="postSaleQuestionItemTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"/>
      </a-tab-pane>
    </a-tabs>
    <a-row v-if="showFlowSubmitButton" style="text-align: center;width: 100%;margin-top: 16px;"><a-button type="primary"  @click="handleOk">提 交</a-button></a-row>
  </a-spin>
</template>

<script>
import pick from 'lodash.pick'
import { getAction, httpAction } from '@/api/manage'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED, validateFormAndTables } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { validateDuplicateValue } from '@/utils/util'

export default {
  name: 'PostSaleQuestionForm',
  mixins: [JEditableTableMixin],
  components: {},
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      model: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        visitor: {
          rules: [{ required: true, message: '请选择回访人' }],
          initialValue: '',
        },
        contactPerson: {
          rules: [{ required: true, message: '请输入用户名称' }],
        },
        contactPersonRole: {
          rules: [{ required: true, message: '请输入用户角色' }],
        },
        questionDate: {
          rules: [{ required: true, message: '请选择问题提出日期' }],
        },
        hopeDate: {
          rules: [{ required: true, message: '请选择期望完成日期' }],
        },
        projectName: {
          rules: [{ required: true, message: '请选择项目' }],
        },
      },
      refKeys: ['postSaleQuestionItem'],
      tableKeys: ['postSaleQuestionItem'],
      activeKey: 'postSaleQuestionItem',
      // 售后问题明细
      postSaleQuestionItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '问题类型',
            key: 'questionType',
            type: FormTypes.select,
            placeholder: '请选择',
            dictCode: 'icm_post_sale_question_type',
            defaultValue: '',
            required: true,
            width: '10%',
          },
          {
            title: '问题描述',
            key: 'questionDesc',
            type: FormTypes.input,
            placeholder: '请输入${title}',
            defaultValue: '',
            required: true,
            width: '90%',
          },
        ],
        columns1: [
          {
            title: '问题类型',
            key: 'questionType',
            type: FormTypes.select,
            placeholder: '请选择',
            width: '10%',
            dictCode: 'icm_post_sale_question_type',
            defaultValue: '',
            disabled: true,
            required: true,
          },
          {
            title: '问题描述',
            key: 'questionDesc',
            type: FormTypes.input,
            placeholder: '请输入${title}',
            defaultValue: '',
            width: '42%',
            disabled: true,
            required: true,
          },
          {
            title: '工时',
            key: 'workHours',
            type: FormTypes.inputNumber,
            placeholder: '请输入${title}',
            width: '8%',
            defaultValue: '0',
          },
          {
            title: '完成人',
            key: 'charger',
            type: FormTypes.sel_user,
            placeholder: '请输入${title}',
            width: '16%',
            defaultValue: '',
          },
          {
            title: '完成时间',
            key: 'completedDate',
            type: FormTypes.date,
            placeholder: '请输入${title}',
            width: '14%',
            defaultValue: '',
          },
          {
            title: '问题状态',
            key: 'questionStatus',
            type: FormTypes.select,
            placeholder: '请输入${title}',
            dictCode: 'icm_post_sale_question_status',
            width: '10%',
            defaultValue: '1',
          },
        ],
      },
      fields: [
        'customerShortName',
        'projectName',
        'projectId',
        'visitResult',
        'visitDate',
        'contactPersonRole',
        'contactPerson',
        'questionDate',
        'hopeDate',
        'visitor',
        'files',
        'projectCharger',
      ],
      url: {
        add: '/postsale/postSaleQuestion/add',
        edit: '/postsale/postSaleQuestion/edit',
        queryById: '/postsale/postSaleQuestion/queryById',
        postSaleQuestionItem: {
          list: '/postsale/postSaleQuestion/queryPostSaleQuestionItemByMainId',
        },
      },
    }
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false,
    },
    //表单模式：false流程表单 true普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false,
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  watch:{
    '$store.state.bpm.bpmSubmitStates': {
      immediate: true,
      handler(val) {
        if (val && val.edit && val.edit === '1') {
          this.handleOk().then(res => {
            if (res) {
              this.$store.commit('BPM_SUBMIT_STATES', { edit: '2' })
            }
          })
        }
      }
    },
  },
  methods: {
    handleOk() {
      const that = this
      return new Promise(((resolve, reject) => {
        /** 触发表单验证 */
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          let url = this.url.add, method = 'post'
          if (this.model.id) {
            url = this.url.edit
            method = 'put'
          }
          that.confirmLoading = true
          httpAction(url, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              resolve(true)
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
          // return this.request(formData)
        }).catch(e => {
          this.$store.commit('BPM_SUBMIT_STATES', {})
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      }))

    },
    addBefore() {
      this.form.resetFields()
      this.postSaleQuestionItemTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      let fieldval = pick(this.model, this.fields)
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.postSaleQuestionItem.list, params, this.postSaleQuestionItemTable)
      }
    },
    /** 查询某个tab的数据 */
    requestSubTableData(url, params, tab, success) {
      tab.loading = true
      getAction(url, params)
        .then((res) => {
          let { result } = res
          let dataSource = []
          if (result) {
            if (Array.isArray(result)) {
              dataSource = result
            } else if (Array.isArray(result.records)) {
              dataSource = result.records
            }
          }
          //查询到数据后，默认问题状态是“已提出”
          dataSource.forEach((v) => {
            if (!v.questionStatus) {
              v.questionStatus = '1'
            }
          })
          tab.dataSource = dataSource
          typeof success === 'function' ? success(res) : ''
        })
        .finally(() => {
          tab.loading = false
        })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        postSaleQuestionItemList: allValues.tablesValue[0].values,
      }
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, this.fields))
    },
  },
}
</script>

<style scoped>
</style>